
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/controller/navigation_controller.dart';
import 'package:interview/servers/question_list.dart';
import 'package:interview/utils/http.dart';
import 'package:interview/utils/logger.dart';

/// 获取QuestionList
Future<QuestionListResponse> fetchRecommendList(BuildContext context) async {
  try {
    // 发起 GET 请求
    final response = await Http.get<Map<String, dynamic>>('question/recommends' , context: context);
    // 检查响应结构
    if (response['success'] == true && response['data'] is Map<String, dynamic>) {
      final data = response['data'] as Map<String, dynamic>;
     // 验证和提取数据
      if (data['rows'] is List && data['pageTotal'] is int) {
        final questions = (data['rows'] as List).map((item) => Question.fromJson(item as Map<String, dynamic>)).toList();
        final pageTotal = data['pageTotal'] as int;
        // 返回封装的结果
        return QuestionListResponse(
          questions: questions,
          total: 5,
          pageTotal: pageTotal,
        );
      } else {
        throw Exception('fetchRecommendList 数据格式错误: 缺少 total/pageTotal 或 rows 字段格式不正确');
      }
    } else {
      throw Exception('响应数据格式错误或未成功: ${response['message']}');
    }
  } catch (e ,stackTrace ) {
    Get.find<NavigationController>().push('/login'); // 这里属于服务端的错误 强制导航到login
    // 错误处理
    Logger.error("获取 fetchRecommendList 失败: $e", tag: 'fetchRecommendList' , stackTrace:stackTrace);
    throw Exception('获取fetchRecommendList失败: $e');
  }
}
